﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace QuanLyPhongKham
{
    public partial class QuanLyVienPhi : BaseUserControl
    {
        private DAL.AccessData m = new DAL.AccessData();
        private doiso.Doisototext doiso = new doiso.Doisototext();
        private string sql = "", user = "", s_mabn = "", s_makp = "", s_form = "", s_mabs = "";
        private long l_maql = 0, l_id = 0;
        private int i_userid = 1, iSohd;
        private bool bEdit = false;
        private decimal d_dongia = 0, d_soluong = 0, d_sotien = 0, d_tongtien = 0;
        private DataSet ds = new DataSet();
        private DataSet dsxml = new DataSet();
        private DataSet dsin = new DataSet();
        private DataTable dtds = new DataTable();
        private DataTable dtgiavp = new DataTable();
        private DataTable dtct = new DataTable();
        private DataTable dtll = new DataTable();
        private DataTable dtxoa = new DataTable();
        private DataTable dtbs = new DataTable();
        public QuanLyVienPhi()
        {
            user = m.user;
            InitializeComponent();
        }
        private void lTen_DoubleClick(object sender, EventArgs e)
        {
            //frmAbout f = new frmAbout(pForm.Location.X,pForm.Location.Y,lTen.Text,m);
            //f.ShowDialog();
            //load_tieude();
        }
        private void QuanLyPhongKham_Load(object sender, EventArgs e)
        {
            var f = this.FormMain.FormLogin;

            if (f.i_userid != 0)
            {
                dsin = m.get_data("select '' as mabn,'' as hoten,'' as namsinh,'' as diachi,'' as khoaphong,'' as tenbs,'' as lydo,0.0 as sotien,'' as bangchu");
                listDsbn.DisplayMember = "HOTEN";
                listDsbn.ValueMember = "MAQL";
                cboSohoadon.DisplayMember = "SOBIENLAI";
                cboSohoadon.ValueMember = "ID";
                dtbs = m.get_data("select ma,hoten from " + user + ".dmbs where nghiviec=0").Tables[0];
                load_sophieu();
                load_tienkham();
                load_ds_chidinh();
                if (dtll.Rows.Count > 0) l_id = long.Parse(cboSohoadon.SelectedValue.ToString());
                load_grid();
                AddGridTableStyle();
                ena_button(true);
                sohoadon.Text = m.get_sobienlai().ToString();
            }
            else Application.Exit();
        }
        private void load_sophieu()
        {
            sql = "select * from " + user + ".v_vienphill where to_char(ngay,'dd/mm/yyyy')='" + ngaylamviec.Text.Substring(0, 10) + "'";
            dtll = m.get_data(sql).Tables[0];
            cboSohoadon.DataSource = dtll;
            iSohd = 0;
            d_tongtien = 0;
            foreach (DataRow r in dtll.Rows)
            {
                iSohd += 1;
                d_tongtien += decimal.Parse(r["sotien"].ToString());
            }
            tongtien.Text = d_tongtien.ToString("###,###,##0");
            tonghd.Text = iSohd.ToString("###,###,##0");
        }
        private void load_grid()
        {
            sql = "select a.id,a.stt,a.mavp,b.ten,a.soluong,round(a.dongia,2) as dongia,round(a.soluong*a.dongia,2) as sotien from " + user + ".v_vienphict a, " + user + ".dmgiavp b where a.mavp=b.id and a.id=" + l_id;
            dtct = m.get_data(sql).Tables[0];
            dataGrid1.DataSource = dtct;
            dtxoa = dtct.Clone();
            sum_sotienban();
        }
        private void load_chiphi()
        {
            sql = "select a.id,a.stt,a.mavp,b.ten,a.soluong,round(a.dongia,2) as dongia,round(a.soluong*a.dongia,2) as sotien,a.ghichu from " + user + ".v_chidinh a, " + user + ".dmgiavp b where a.mavp=b.id and a.paid=0 and a.maql=" + l_maql;
            if (s_mabs != "") sql += " and a.mabs='" + s_mabs + "'";
            decimal s_stt = 0;
            s_form = "";
            foreach (DataRow r in m.get_data(sql).Tables[0].Rows)
            {
                s_form += r["ghichu"].ToString();
                s_stt += decimal.Parse(r["sotien"].ToString());
                updec_dtct(dtct,long.Parse(r["id"].ToString()),int.Parse(r["stt"].ToString()),int.Parse(r["mavp"].ToString()),r["ten"].ToString(),decimal.Parse(r["soluong"].ToString()),decimal.Parse(r["dongia"].ToString()),decimal.Parse(r["sotien"].ToString()));
            }
            dtct.AcceptChanges();
            sum_sotienban();
        }
        private void load_head()
        {
            s_form = "";
            DataRow r = m.getrowbyid(dtll, "sobienlai=" + long.Parse(sohoadon.Text));
            if(r!=null)
            {
                l_maql = long.Parse(r["maql"].ToString());
                l_id=long.Parse(r["id"].ToString());
                s_form = r["ghichu"].ToString();
                s_mabn = r["mabn"].ToString();
                mabs.Text = r["mabs"].ToString();
                DataRow r1 = m.getrowbyid(dtbs, "ma='" + mabs.Text + "'");
                if (r1 != null) tenbs.Text = r1["hoten"].ToString();
                mabn.Text = s_mabn;
                load_mabn();
                load_grid();
            }
        }
        private void sum_sotienban()
        {
            decimal d_tongcong = 0;
            foreach (DataRow r in dtct.Select("soluong>0"))
                d_tongcong += decimal.Parse(r["soluong"].ToString()) * decimal.Parse(r["dongia"].ToString());
            sotien.Text = d_tongcong.ToString("###,###,###,##0");
            string s_chu = doiso.Doiso_Unicode(Convert.ToInt64(d_tongcong).ToString());
            bangchu.Text = s_chu;
        }
        private void updec_dtct(DataTable dt,long id,int stt,int mavp,string ten,decimal soluong,decimal dongia,decimal sotien)
        {
            DataRow r = m.getrowbyid(dt, "mavp=" + mavp);
            if (r == null)
            {
                DataRow rr = dt.NewRow();
                rr["id"] = id;
                rr["stt"] = m.get_stt(dt);
                rr["mavp"] = mavp;
                rr["ten"] = ten;
                rr["soluong"] = soluong;
                rr["dongia"] = dongia;
                rr["sotien"] = sotien;
                dt.Rows.Add(rr);
            }
            else 
            {
                r["soluong"] = soluong;
                r["dongia"] = dongia;
                r["sotien"] = sotien;
            }
            dt.AcceptChanges();
        }
        private void AddGridTableStyle()
        {
            DataGridColoredTextBoxColumn TextCol;
            delegateGetColorRowCol de = new delegateGetColorRowCol(MyGetColorRowCol);
            DataGridTableStyle ts = new DataGridTableStyle();
            ts.MappingName = dtct.TableName;
            ts.AlternatingBackColor = Color.Linen;
            ts.BackColor = Color.GhostWhite;
            ts.ForeColor = Color.MidnightBlue;
            ts.GridLineColor = SystemColors.Control;
            ts.HeaderBackColor = SystemColors.Control;
            ts.HeaderForeColor = Color.Navy;
            ts.SelectionBackColor = Color.Teal;
            ts.SelectionForeColor = Color.White;
            ts.ReadOnly = false;
            ts.RowHeaderWidth = 5;

            TextCol = new DataGridColoredTextBoxColumn(de, 0);
            TextCol.MappingName = "stt";
            TextCol.HeaderText = "Stt";
            TextCol.Width = 30;
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 1);
            TextCol.MappingName = "mavp";
            TextCol.HeaderText = "mavp";
            TextCol.Width = 0;
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 2);
            TextCol.MappingName = "ten";
            TextCol.HeaderText = "Tên dịch vụ khám";
            TextCol.Width = 600;
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 3);
            TextCol.MappingName = "soluong";
            TextCol.HeaderText = "Số lượng";
            TextCol.Width = 140;
            TextCol.Format = "###,###,##0";
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 4);
            TextCol.MappingName = "dongia";
            TextCol.HeaderText = "Đơn giá";
            TextCol.Width = 160;
            TextCol.Format = "###,###,##0";
            TextCol.ReadOnly = true;
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);

            TextCol = new DataGridColoredTextBoxColumn(de, 5);
            TextCol.MappingName = "sotien";
            TextCol.HeaderText = "Thành tiền";
            TextCol.Width = 160;
            TextCol.Format = "###,###,##0";
            ts.GridColumnStyles.Add(TextCol);
            dataGrid1.TableStyles.Add(ts);
            
        }
        public Color MyGetColorRowCol(int row, int col)
        {
            Color c = Color.Navy;
            try
            {
                if (row == dataGrid1.CurrentRowIndex)
                {
                    dataGrid1.Select(row);
                    c = Color.White;
                }
            }
            catch
            {
            }
            return c;
        }
        public delegate Color delegateGetColorRowCol(int row, int col);
        public class DataGridColoredTextBoxColumn : DataGridTextBoxColumn
        {
            private delegateGetColorRowCol _getColorRowCol;
            private int _column;
            public DataGridColoredTextBoxColumn(delegateGetColorRowCol getcolorRowCol, int column)
            {
                _getColorRowCol = getcolorRowCol;
                _column = column;
            }
            protected override void Paint(System.Drawing.Graphics g, System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush foreBrush, bool alignToRight)
            {
                try
                {
                    foreBrush = new SolidBrush(_getColorRowCol(rowNum, this._column));
                }
                catch { }
                finally
                {
                    base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);
                }
            }
        }
        private void load_tienkham()
        {
            cboTienkham.DisplayMember = "TEN";
            cboTienkham.ValueMember = "ID";
            dtgiavp = m.get_data("select * from " + user + ".dmgiavp").Tables[0];
            cboTienkham.DataSource = dtgiavp;
        }
        private void load_tieude()
        {
            if (System.IO.File.Exists(@"..\..\..\xml\thongso.xml"))
            {
                dsxml.ReadXml(@"..\..\..\xml\thongso.xml");
                lTen.Text = dsxml.Tables[0].Rows[0]["c1"].ToString().ToUpper();
                lDiachi.Text = dsxml.Tables[0].Rows[0]["c2"].ToString();
            }
        }
        private void mabn_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    ComboBox cb = (ComboBox)sender;
                    if (cb.SelectedIndex == -1) cb.SelectedIndex = 0;
                    SendKeys.Send("{Tab}{F4}");
                }
                catch { SendKeys.Send("{Tab}{F4}"); }
            }
        }
        private void butLuu_Click(object sender, EventArgs e)
        {
            if(l_maql==0)
            {
                MessageBox.Show("Nhập thông tin bệnh nhân!"); mabn.Focus(); return;
            }
            if (dtct.Rows.Count == 0) return;
            long l_sobienlai = m.get_sobienlai_thuvp(long.Parse(sohoadon.Text));
            sohoadon.Text = l_sobienlai.ToString();
            l_id = (l_id == 0) ? m.get_capid : l_id;
            if (!m.upd_vienphill(l_id, long.Parse(sohoadon.Text), mabn.Text, l_maql, makp.Text, ngaylamviec.Text.Substring(0, 10), i_userid, s_form,decimal.Parse(sotien.Text), 0, mabs.Text))
            {
                MessageBox.Show("Không cập nhật được thông tin thu viện phí",DAL.AccessData.Msg);
                return;
            }
            if (bEdit)
            {
                foreach (DataRow r in dtxoa.Rows)
                {
                    m.upd_theodoisua(m.get_capid_theodoisua, mabn.Text, l_maql, int.Parse(r["mavp"].ToString()), r["ten"].ToString(), decimal.Parse(r["soluong"].ToString()), i_userid, "VP", "v_vienphict", 0, 0, 1);
                    m.execute_data("delete from " + user + ".v_vienphict where id=" + l_id + " and mavp=" + int.Parse(r["mavp"].ToString()));
                    m.execute_data("update " + user + ".v_chidinh set paid=0 where mavp=" + long.Parse(r["mavp"].ToString()) + " and maql=" + l_maql);
                }
            }
            foreach (DataRow r in dtct.Rows)
            {
                m.upd_vienphict(l_id, int.Parse(r["stt"].ToString()), 2, long.Parse(r["mavp"].ToString()), decimal.Parse(r["soluong"].ToString()), decimal.Parse(r["dongia"].ToString()), long.Parse(r["id"].ToString()));
                m.execute_data("update " + user + ".v_chidinh set paid=1 where mavp=" + long.Parse(r["mavp"].ToString()) + " and maql=" + l_maql);
            }
            load_sophieu();
            if (cboSohoadon.Items.Count > 0) cboSohoadon.SelectedIndex = dtll.Rows.Count - 1;
            //if (cboSohoadon.Items.Count > 0) cboSohoadon.SelectedValue = l_id;
            load_grid();
            load_ds_chidinh();
            ena_button(true);
        }
        private void butKetthuc_Click(object sender, EventArgs e)
        {
            //if (MessageBox.Show("Bạn có muốn kết thúc chương trình không?",DAL.AccessData.Msg,MessageBoxButtons.YesNo,MessageBoxIcon.Information,MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            //{
            //    this.Close();
            //}
        }
        private void butMoi_Click(object sender, EventArgs e)
        {
            dtct.Clear(); l_id = 0; l_maql = 0; empty_text();
            ena_button(false);
            sohoadon.Text = m.get_sobienlai().ToString();
            load_ds_chidinh();
            mabn.Focus();
        }
        private void empty_text()
        {
            mabn.Text = ""; hoten.Text = ""; namsinh.Text = ""; mabs.Text = ""; tenbs.Text = ""; makp.Text = ""; tenkp.Text = "";
            diachi.Text = ""; stt.Text = ""; s_mabs = "";
        }
        private bool load_mabn()
        {
            bool ret = false;
            sql = "select a.mabn,a.maql,b.hoten,b.namsinh,b.phai,trim(b.diachi||' '||g.tenpxa||' '||f.tenquan||' '||e.tentt) as diachi,a.makp,d.tenkp from " + user + ".benhanpk a," + user + ".btdbn b, " + user + ".btdkp d, " + user + ".btdtt e, " + user + ".btdquan f, " + user + ".btdpxa g where a.mabn=b.mabn and a.makp=d.makp and b.matt=e.matt and b.maqu=f.maqu and b.maphuongxa=g.maphuongxa and a.maql='" + l_maql + "'";//and a.done=1 
            foreach (DataRow r in m.get_data(sql).Tables[0].Rows)
            {
                mabn.Text = r["mabn"].ToString();
                hoten.Text = r["hoten"].ToString();
                namsinh.Text = r["namsinh"].ToString();
                cboGioitinh.SelectedIndex = int.Parse(r["phai"].ToString());
                diachi.Text = r["diachi"].ToString();
                makp.Text = r["makp"].ToString();
                tenkp.Text = r["tenkp"].ToString();
                ret = true;
                break;
            }
            return ret;
        }
        private void load_ds_chidinh()
        {
            sql = "select distinct a.mabn,b.hoten,a.maql,a.mabs from " + user + ".v_chidinh a," + user + ".btdbn b where a.mabn=b.mabn and to_char(a.ngay,'dd/mm/yyyy')='" + m.ngayhienhanh_server.Substring(0, 10) + "' and a.paid = 0";// order by a.ngay desc,a.maql desc
            dtds=m.get_data(sql).Tables[0];
            listDsbn.DataSource = dtds;
            listDsbn.ColumnWidths[0] = 60;
            listDsbn.ColumnWidths[1] = 300;
            listDsbn.ColumnWidths[2] = 0;
            pDscho.Visible = listDsbn.Items.Count > 0;
        }
        private void MaskDigit(KeyPressEventArgs e)
        {
            if (Char.IsDigit(e.KeyChar) || e.KeyChar == 8) e.Handled = false;
            else e.Handled = true;
        }

        private void mabn_KeyPress(object sender, KeyPressEventArgs e)
        {
            MaskDigit(e);
        }

        private void mabn2_Validated(object sender, EventArgs e)
        {
            if (mabn.Text.Trim() == "" && mabn.Text.Trim().Length < 3)
            {
                return;
            }
            else
            {
                mabn.Text = mabn.Text.Substring(0, 2) + mabn.Text.Substring(2).PadLeft(6, '0');
                s_mabn = mabn.Text;
            }
            if (load_mabn())
            {
                load_chiphi();
                if (dtct.Rows.Count > 0) dataGrid1.Focus();
            }
            else 
            {
                MessageBox.Show("Số liệu chưa được chuyển xuống viện phí!", DAL.AccessData.Msg);
                mabn.Focus(); return;
            }
        }
      
        private bool IsLoaded(string frm)
        {
            //Form[] afrm = this.MdiChildren;
            //foreach (Form f in afrm)
            //{
            //    if (f.Name.Equals(frm)) { f.Activate(); f.BringToFront(); pForm.SendToBack(); pPhieukham.Visible = false; return true; }
            //}
            return false;
        }

        private void sohoadon_KeyPress(object sender, KeyPressEventArgs e)
        {
            MaskDigit(e);
        }
        private void ena_button(bool ena)
        {
            sohoadon.Visible = !ena;
            cboSohoadon.Visible = ena;
            butMoi.Enabled = ena;
            butLuu.Enabled = !ena;
            butXoa.Enabled = !ena;
            butThem.Enabled = !ena;
            butSua.Enabled = ena;
            butHuy.Enabled = ena;
            butBoqua.Enabled = !ena;
            butIn.Enabled = ena;
            butInphieukham.Enabled = ena;
            butKetthuc.Enabled = ena;
            listDsbn.Enabled = !ena;
            //CurrencyManager cm = (CurrencyManager)BindingContext[dataGrid1.DataSource, dataGrid1.DataMember];
            //DataView dv = (DataView)cm.List;
            //dv.AllowNew = false;
            //dv.AllowDelete = false;
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Action == TreeViewAction.ByMouse || e.Action == TreeViewAction.ByKeyboard)
            {
                try
                {
                    d_dongia = 0; d_sotien = 0; d_dongia = 0;
                    dtct.Clear(); l_id = 0; l_maql = 0; empty_text();
                    sohoadon.Text = m.get_sobienlai().ToString();
                    string s = e.Node.FullPath.ToString();
                    s_mabn = s.Substring(s.Length - 8);
                    l_maql = long.Parse(e.Node.Tag.ToString());
                    mabn.Text = s_mabn;
                    if (l_maql != 0)
                    {
                        load_mabn();
                        load_chiphi();
                        ena_button(false);
                    }
                }
                catch { }
            }
        }

        private void butThem_Click(object sender, EventArgs e)
        {
            //if (cboTienkham.SelectedIndex != -1 && l_maql != 0)
            //{
            //    updec_dtct(dtct, 0, m.get_stt(dtct), int.Parse(cboTienkham.SelectedValue.ToString()), cboTienkham.Text, 1, decimal.Parse(dongia.Text), decimal.Parse(dongia.Text));
            //    dtct.AcceptChanges();
            //}
        }

        private void butXoa_Click(object sender, EventArgs e)
        {
            //if (stt.Text == "")
            //{
            //    MessageBox.Show("Chọn dịch vụ cần xoá!", DAL.AccessData.Msg); return;
            //}
            //updec_dtct(dtxoa, l_id, int.Parse(stt.Text), int.Parse(cboTienkham.SelectedValue.ToString()), cboTienkham.Text, d_soluong, d_dongia, d_sotien);
            //m.delrec(dtct, "mavp=" + cboTienkham.SelectedValue.ToString());
            //dtct.AcceptChanges();
        }

        private void dataGrid1_CurrentCellChanged(object sender, EventArgs e)
        {
            try 
            {
                //foreach (DataRow r in dtct.Rows)
                //{
                //    r["sotien"] = decimal.Parse(r["soluong"].ToString()) * decimal.Parse(r["dongia"].ToString());
                //}
                reft_text();
                sum_sotienban();
            }
            catch { }
            
        }
        private void reft_text()
        {
            try 
            {
                int i = dataGrid1.CurrentCell.RowNumber;
                stt.Text = dataGrid1[i, 1].ToString();
                d_soluong = decimal.Parse(dataGrid1[i, 3].ToString());
                d_dongia = decimal.Parse(dataGrid1[i, 4].ToString());
                d_sotien = d_soluong * d_dongia;
                //cboTienkham.SelectedValue = int.Parse(dataGrid1[i, 1].ToString());
                d_dongia = decimal.Parse(dataGrid1[i, 4].ToString());
                dongia.Text = d_dongia.ToString("###,###,##0");
                dongia.Focus();
            }
            catch { }
        }
        private void cboTienkham_SelectedIndexChanged(object sender, EventArgs e)
        {
            try 
            {
                decimal d_dongia=0;
                DataRow r=m.getrowbyid(dtgiavp,"id="+int.Parse(cboTienkham.SelectedValue.ToString()));
                if(r!=null)
                {
                    d_dongia=decimal.Parse(r["dongia"].ToString());
                    dongia.Text=d_dongia.ToString("###,###,##0");
                }
            }
            catch { }
        }

        private void butBoqua_Click(object sender, EventArgs e)
        {
            if (cboSohoadon.Items.Count > 0)
            {
                l_id = long.Parse(cboSohoadon.SelectedValue.ToString());
                sohoadon.Text = cboSohoadon.Text;
                load_head();
                load_grid();
            }
            else l_id = 0;
            ena_button(true);
        }

        private void QuanLyVienPhi_SizeChanged(object sender, EventArgs e)
        {
            bNut.Location = new Point((this.Width - 954) / 2 - 10, 2);
        }

        private void butSua_Click(object sender, EventArgs e)
        {
            ena_button(false);
            bEdit = true;
            dtxoa.Clear();
        }

        private void cboSohoadon_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cboSohoadon.Items.Count > 0)
                {
                    sohoadon.Text = cboSohoadon.Text;
                    l_id = long.Parse(cboSohoadon.SelectedValue.ToString());
                    load_head();
                }
            }
            catch { }
        }

        private void butHuy_Click(object sender, EventArgs e)
        {
            if (l_id == 0) return;
            if (MessageBox.Show("Bạn có đồng ý huỷ hoá đơn này không?", DAL.AccessData.Msg, MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                foreach (DataRow r in dtct.Rows)
                {
                    m.execute_data("delete from "+user+".v_vienphict where id="+l_id+" and mavp="+int.Parse(r["mavp"].ToString()));
                    m.execute_data("update " + user + ".v_chidinh set paid=0 where maql=" + l_maql + " and mavp=" + int.Parse(r["mavp"].ToString()));
                }
                m.execute_data("delete from " + user + ".v_vienphill where id=" + l_id);
                load_sophieu();
                load_grid();
                load_head();
            }
        }

        private void timkiem_TextChanged(object sender, EventArgs e)
        {
            if (this.ActiveControl == timkiem)
            {
                CurrencyManager cm = (CurrencyManager)BindingContext[cboSohoadon.DataSource];
                DataView dv = (DataView)cm.List;
                dv.RowFilter = "sobienlai like '" + timkiem.Text + "%'";
            }
        }

        private void butIn_Click(object sender, EventArgs e)
        {
            if (dtct.Rows.Count == 0) return;
            dsin.Clear();
            DataRow rr = dsin.Tables[0].NewRow();
            rr["mabn"] = mabn.Text;
            rr["hoten"] = hoten.Text;
            rr["namsinh"] = namsinh.Text;
            rr["diachi"] = diachi.Text;
            rr["khoaphong"] = tenkp.Text;
            rr["tenbs"] = tenbs.Text;
            rr["lydo"] = get_lydothu();//"Thu tiền khám bệnh";
            rr["sotien"] = sotien.Text;
            rr["bangchu"] = bangchu.Text;
            dsin.Tables[0].Rows.Add(rr);
            dsin.AcceptChanges();
            dsin.WriteXml(@"..\v_bienlai.xml", XmlWriteMode.WriteSchema);
            frmReport f = new frmReport(m, dsin.Tables[0], "", "v_bienlai.rpt", "", "", "", "", ngaylamviec.Text.Substring(0, 10), "", "", "", "", "", "", "");
            this.FormMain.OpenTab("Biên Lai", f);
        }
        private string get_lydothu()
        {
            string s_lydo = "";
            foreach (DataRow r in dtct.Rows)
            {
                DataRow r1 = m.getrowbyid(dtgiavp, "id=" + int.Parse(r["mavp"].ToString()));
                if (r1 != null)
                {
                    s_lydo += r1["ten"].ToString().ToLower() + ", ";
                }
            }
            return s_lydo = "Thu " + s_lydo.Trim().Trim(',');
        }
        private void load_report()
        {
            DataSet dst = new DataSet();
            string [] var_form = s_form.Split(',');
            string s_report = "";
            for (int ii = 0; ii < var_form.Length; ii++)
            {
                sql = "";
                switch (var_form[ii].ToString())
                {
                    case "pKhamvu":
                        sql = "select a.*,b.hoten,b.namsinh,b.phai,b.cholam,trim(b.diachi||' '||e.tenpxa||' '||d.tenquan||' '||c.tentt) as diachi from " + user + ".ba_khamvu a, " + user + ".btdbn b, " + user + ".btdtt c, " + user + ".btdquan d, " + user + ".btdpxa e ";
                        sql += " where a.mabn=b.mabn and b.matt=c.matt and b.maqu=d.maqu and b.maphuongxa=e.maphuongxa and a.mabn='" + s_mabn + "' and a.maql=" + l_maql;
                        dst = m.get_data(sql);
                        s_report = "ba_khamvu.rpt";
                        break;
                    case "pKhampk":
                        sql = "select a.*,b.hoten,b.namsinh,b.phai,b.cholam,trim(b.diachi||' '||e.tenpxa||' '||d.tenquan||' '||c.tentt) as diachi from " + user + ".ba_khampk a, " + user + ".btdbn b, " + user + ".btdtt c, " + user + ".btdquan d, " + user + ".btdpxa e ";
                        sql += " where a.mabn=b.mabn and b.matt=c.matt and b.maqu=d.maqu and b.maphuongxa=e.maphuongxa and a.mabn='" + s_mabn + "' and a.maql=" + l_maql;
                        dst = m.get_data(sql);
                        s_report = "ba_khampk.rpt";
                        break;
                    case "pKhamthai":
                        sql = "select to_char(a.dukiensinh,'dd/mm/yyyy') as dukiensinh,a.*,b.hoten,b.namsinh,b.phai,b.cholam,trim(b.diachi||' '||e.tenpxa||' '||d.tenquan||' '||c.tentt) as diachi from " + user + ".ba_khamthai a, " + user + ".btdbn b, " + user + ".btdtt c, " + user + ".btdquan d, " + user + ".btdpxa e ";
                        sql += " where a.mabn=b.mabn and b.matt=c.matt and b.maqu=d.maqu and b.maphuongxa=e.maphuongxa and a.mabn='" + s_mabn + "' and a.maql=" + l_maql;
                        dst = m.get_data(sql);
                        s_report = "ba_khamthai.rpt";
                        break;
                    case "pHiemmuon":
                        sql = "select a.*,b.hoten,b.namsinh,b.phai,b.cholam,trim(b.diachi||' '||e.tenpxa||' '||d.tenquan||' '||c.tentt) as diachi from " + user + ".ba_hiemmuon a, " + user + ".btdbn b, " + user + ".btdtt c, " + user + ".btdquan d, " + user + ".btdpxa e ";
                        sql += " where a.mabn=b.mabn and b.matt=c.matt and b.maqu=d.maqu and b.maphuongxa=e.maphuongxa and a.mabn='" + s_mabn + "' and a.maql=" + l_maql;
                        dst = m.get_data(sql);
                        s_report = "ba_hiemmuon.rpt";
                        break;
                    case "pSieuam":
                        sql = "select a.*,b.hoten,b.namsinh,b.phai,b.cholam,trim(b.diachi||' '||e.tenpxa||' '||d.tenquan||' '||c.tentt) as diachi from " + user + ".ba_sieuam4d a, " + user + ".btdbn b, " + user + ".btdtt c, " + user + ".btdquan d, " + user + ".btdpxa e ";
                        sql += " where a.mabn=b.mabn and b.matt=c.matt and b.maqu=d.maqu and b.maphuongxa=e.maphuongxa and a.mabn='" + s_mabn + "' and a.maql=" + l_maql;
                        dst = m.get_data(sql);
                        s_report = "ba_sieuam4d.rpt";
                        break;
                    case "pSieuam_tn":
                        sql = "select a.*,b.hoten,b.namsinh,b.phai,b.cholam,trim(b.diachi||' '||e.tenpxa||' '||d.tenquan||' '||c.tentt) as diachi from " + user + ".ba_sieuamthai a, " + user + ".btdbn b, " + user + ".btdtt c, " + user + ".btdquan d, " + user + ".btdpxa e ";
                        sql += " where a.mabn=b.mabn and b.matt=c.matt and b.maqu=d.maqu and b.maphuongxa=e.maphuongxa and a.mabn='" + s_mabn + "' and a.maql=" + l_maql;
                        dst = m.get_data(sql);
                        s_report = "ba_sieuamthai_nghen.rpt";
                        break;
                    case "pSieuam_th":
                        sql = "select a.*,b.hoten,b.namsinh,b.phai,b.cholam,trim(b.diachi||' '||e.tenpxa||' '||d.tenquan||' '||c.tentt) as diachi from " + user + ".ba_sieuamthai_3thang a, " + user + ".btdbn b, " + user + ".btdtt c, " + user + ".btdquan d, " + user + ".btdpxa e ";
                        sql += " where a.mabn=b.mabn and b.matt=c.matt and b.maqu=d.maqu and b.maphuongxa=e.maphuongxa and a.mabn='" + s_mabn + "' and a.maql=" + l_maql;
                        dst = m.get_data(sql);
                        s_report = "ba_sieuamthai.rpt";
                        break;
                    case "pSieuam_pk":
                        sql = "select a.*,b.hoten,b.namsinh,b.phai,b.cholam,trim(b.diachi||' '||e.tenpxa||' '||d.tenquan||' '||c.tentt) as diachi from " + user + ".ba_sieuampk a, " + user + ".btdbn b, " + user + ".btdtt c, " + user + ".btdquan d, " + user + ".btdpxa e ";
                        sql += " where a.mabn=b.mabn and b.matt=c.matt and b.maqu=d.maqu and b.maphuongxa=e.maphuongxa and a.mabn='" + s_mabn + "' and a.maql=" + l_maql;
                        dst = m.get_data(sql);
                        s_report = "ba_sieuampk.rpt";
                        break;
                    case "pTheodoi":
                        sql = "select a.*,b.hoten,b.namsinh,b.phai,b.cholam,trim(b.diachi||' '||e.tenpxa||' '||d.tenquan||' '||c.tentt) as diachi from " + user + ".ba_theodoitimthai a, " + user + ".btdbn b, " + user + ".btdtt c, " + user + ".btdquan d, " + user + ".btdpxa e ";
                        sql += " where a.mabn=b.mabn and b.matt=c.matt and b.maqu=d.maqu and b.maphuongxa=e.maphuongxa and a.mabn='" + s_mabn + "' and a.maql=" + l_maql;
                        dst = m.get_data(sql);
                        s_report = "ba_theodoithai.rpt";
                        break;
                    case "pSieuam4D":
                        sql = "select a.*,b.hoten,b.namsinh,b.phai,b.cholam,trim(b.diachi||' '||e.tenpxa||' '||d.tenquan||' '||c.tentt) as diachi from " + user + ".ba_sieuammau a, " + user + ".btdbn b, " + user + ".btdtt c, " + user + ".btdquan d, " + user + ".btdpxa e ";
                        sql += " where a.mabn=b.mabn and b.matt=c.matt and b.maqu=d.maqu and b.maphuongxa=e.maphuongxa and a.mabn='" + s_mabn + "' and a.maql=" + l_maql;
                        dst = m.get_data(sql);
                        s_report = "ba_sieuammau.rpt";
                        break;
                    case "pSieuam_12":
                        sql = "select a.*,b.hoten,b.namsinh,b.phai,b.cholam,trim(b.diachi||' '||e.tenpxa||' '||d.tenquan||' '||c.tentt) as diachi from " + user + ".ba_sieuam4d_12tuan a, " + user + ".btdbn b, " + user + ".btdtt c, " + user + ".btdquan d, " + user + ".btdpxa e ";
                        sql += " where a.mabn=b.mabn and b.matt=c.matt and b.maqu=d.maqu and b.maphuongxa=e.maphuongxa and a.mabn='" + s_mabn + "' and a.maql=" + l_maql;
                        dst = m.get_data(sql);
                        s_report = "ba_sieuam4d_12tuan.rpt";
                        break;
                    case "pttt": 
                        sql = "select a.*,b.hoten,b.namsinh,b.phai,b.cholam,trim(b.diachi||' '||e.tenpxa||' '||d.tenquan||' '||c.tentt) as diachi from " + m.user + ".pttt a, " + m.user + ".btdbn b, " + m.user + ".btdtt c, " + m.user + ".btdquan d, " + m.user + ".btdpxa e ";
                        sql += " where a.mabn=b.mabn and b.matt=c.matt and b.maqu=d.maqu and b.maphuongxa=e.maphuongxa and a.id=" + l_maql;
                        s_report = "rptPttt.rpt";
                        dst = m.get_data(sql);
                        break;
                }
                if (sql != "")
                {
                    if (dst.Tables[0].Rows.Count == 0) continue;
                    DataColumn dc = new DataColumn("Image", typeof(byte[]));
                    dst.Tables[0].Columns.Add(dc);
                    if (File.Exists("..\\..\\..\\chuky\\" + mabs.Text + ".bmp"))
                    {
                        FileStream fstr = new FileStream("..\\..\\..\\chuky\\" + mabs.Text + ".bmp", FileMode.Open, FileAccess.Read);
                        byte[] image = new byte[fstr.Length];
                        fstr.Read(image, 0, System.Convert.ToInt32(fstr.Length));
                        fstr.Close();
                        foreach (DataRow r1 in dst.Tables[0].Rows) r1["Image"] = image;
                    }
                    dst.WriteXml(@"..\pttt.xml", XmlWriteMode.WriteSchema);
                    frmReport f = new frmReport(m, dst.Tables[0], "", s_report, "", "", "", "Bs. " + tenbs.Text, ngaylamviec.Text.Substring(0, 10), "", "", "", "", "", "", "");
                    //f.ShowDialog();
                    this.FormMain.OpenTab("Báo cáo", f);
                }
            }
        }

        private void butInphieukham_Click(object sender, EventArgs e)
        {
            if (l_maql == 0) return;
            if (s_form == "")
            {
                MessageBox.Show("Bệnh nhân không có phiếu kết quả!",DAL.AccessData.Msg);
                return;
            }
            load_report();
        }

        private void mnuBaocao_Click(object sender, EventArgs e)
        {
            frmBangKeThuTien f = new frmBangKeThuTien(m);
            //f.ShowDialog();
        }

        private void dongia_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                butThem.Focus();
            }
        }

        private void listDsbn_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                d_dongia = 0; d_sotien = 0; d_dongia = 0; s_mabs = "";
                dtct.Clear(); l_id = 0; l_maql = 0; empty_text();
                sohoadon.Text = m.get_sobienlai().ToString();
                l_maql = long.Parse(listDsbn.SelectedValue.ToString());
                if (l_maql != 0)
                {
                    s_mabs = m.getrowbyid(dtds, "maql=" + l_maql)["mabs"].ToString();
                    mabs.Text = s_mabs;
                    DataRow nr = m.getrowbyid(dtbs, "ma='" + s_mabs + "'");
                    if (nr != null) tenbs.Text = nr["hoten"].ToString();
                    load_mabn();
                    load_chiphi();
                    ena_button(false);
                }
                ////
                //s_mabn = s.Substring(s.Length - 8);
                //l_maql = long.Parse(e.Node.Tag.ToString());
                //mabn.Text = s_mabn;
                //if (l_maql != 0)
                //{
                //    load_mabn();
                //    load_chiphi();
                //    ena_button(false);
                //}
            }
            catch { }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (this.ActiveControl == textBox1 && textBox1.Text != "Tìm kiếm")
            {
                CurrencyManager cm = (CurrencyManager)BindingContext[listDsbn.DataSource];
                DataView dv = (DataView)cm.List;
                dv.RowFilter = "hoten like '%" + textBox1.Text + "%'";
            }
        }

        private void textBox1_MouseDown(object sender, MouseEventArgs e)
        {
            if (textBox1.Text == "Tìm kiếm")
            {
                textBox1.Text = "";
            }
        }

        private void textBox1_Validated(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                textBox1.Text = "Tìm kiếm";
            }
        }

        private void butTim_Click(object sender, EventArgs e)
        {
            frmTimhoadon f = new frmTimhoadon(m);
            //f.ShowDialog();
        }
    }
}